const express = require('express');
const router = express.Router();
const { success: handlerSuccess } = require('./resultHandler');
const demo = require('./demo');
const { get } = require('./minidb');
const example = require('./user.js')

// 创建用户
router.post('/users', (req, res) => {
  const { username, age, hobby } = req.body;
  example.add({ username, age, hobby })
    .then((id) => {
      res.send({ "code": 0, "msg": 'ok', "data": id })
    })
    .catch((error) => {
      console.log(error);
      res.send({ "code": -1, "msg": error })
    })
})

// 删除用户
router.delete('/users/:id', (req, res) => {
  const { id } = req.params
  example.delete({ id })
    .then(() => {
      res.send({ "code": 0, "msg": 'ok' })
    })
    .catch((error) => {
      res.send({ "code": -1, "msg": error })
    })
})

// 删除全部用户
router.delete('/users', (req, res) => {
  example.delelteAll()
    .then(() => {
      res.send({ "code": 0, "msg": 'ok' })
    })
    .catch((error) => {
      res.send({ "code": -1, "msg": error })
    })
})

// 更改用户信息
router.put('/users', (req, res) => {
  const id = req.body.id
  const {username,age,hobby} = req.body.obj
  example.update(id, {username,age,hobby})
    .then(() => {
      res.send({ "code": 0, "msg": 'ok' })
    })
    .catch((error) => {
      res.send({ "code": -1, "msg": error })
    })
})

// 获取用户
router.get('/users', (req, res) => {
  const msg = req.query
  const { perpage, page } = req.headers
  example.get(msg, { perpage, page })
    .then((obj) => {
      res.send({
        "code": 0,
        "msg": 'ok',
        "page": req.headers.page,
        "perPage": req.headers.perpage,
        "pageCount": obj.pageCount,
        "total": obj.total,
        "data": obj.data
      })
    })
    .catch((error) => {
      res.send({ "code": -1, "msg": error })
    })
})

module.exports.install = function (app) {
  // 路由根目录，可注册多个
  app.use('/', router);
};
